package com.changgou.web.seckill.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.seckill.feign.SeckillOrderFeign;
import com.changgou.web.seckill.util.CookieUtil;
import com.changgou.web.seckill.util.RandomUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @Author: HuangFu
 * @Date: 2020/2/24 17:17
 * @Description:
 */
@RestController
@RequestMapping("/wseckillorder")
public class SeckillOrderController {

    @Autowired
    private SeckillOrderFeign seckillOrderFeign;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 订单秒杀
     * @param time
     * @param id
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestParam("time") String time, @RequestParam("id") Long id,String random){
        String redisRandom = (String) redisTemplate.boundValueOps(readCookie() + random).get();
        //校验页面码是否准确
        if(StringUtils.isEmpty(redisRandom) || !redisRandom.equals(random)){
            return new Result(false,StatusCode.ERROR,"无效访问");
        }
        return seckillOrderFeign.add(time,id);
    }
    @GetMapping("/getToken")
    public Result getToken(){
        //获取随机数
        String randomString = RandomUtil.getRandomString();
        //读取 cookie
        String uid = this.readCookie();
        //设置随机编码
        redisTemplate.boundValueOps(uid+randomString).set(randomString,10, TimeUnit.SECONDS);
        return new Result(true, StatusCode.OK,"获取页面随机码",randomString);
    }

    /**
     * 读取cookie uid
     * @return
     */
    private String readCookie(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return CookieUtil.readCookie(request, "uid").get("uid");
    }


}
